package com.longy.gulimall.product.controller;

import com.longy.common.utils.R;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * 首页控制器
 *
 * @author Administrator
 * @date 2023/04/05
 */
@RestController
@RequestMapping("index")
public class IndexController {
    @Autowired
    private RedissonClient redisson;

    @GetMapping("/")
    public String hello() {
        RLock lock = redisson.getLock("redisson-lock");
        lock.lock();
        try {
            System.out.println("redisson获得锁。。。" + Thread.currentThread().getName());
            Thread.sleep(40000);
        } catch (Exception e) {

        } finally {
            System.out.println("redisson释放。。。" + Thread.currentThread().getName());
            lock.unlock();
        }

        return "ok";
    }

    @GetMapping("/lockDoor")
    public String lockDoor() {
        RCountDownLatch countDownLatch = redisson.getCountDownLatch("lockDoor");
        countDownLatch.trySetCount(10l);
        System.out.println("放假了");
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                Random random = new Random();
                int nextInt = random.nextInt(10000);
                try {
                    Thread.sleep(nextInt);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("班级" + finalI + "放假了");
                countDownLatch.countDown();
            }).start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("所有班级已走完，锁门.............");
        return "ok";
    }

}
